<?php
/**
 * 数据库操作类
 */
class Db 
{
	public $table;
	public $db;
	public function __construct($table=null)
	{
		$this->table = $table;
		try {
			$this->db = @new PDO("mysql:host=".config('db_host').";dbname=".config('db_name').";charset=utf8",config('db_username'),config('db_password'));
		} catch (PdoException $e) {
			echo "数据库链接不成功";
		}
	}

	public function add($data)
	{
		$key = implode(",",array_keys($data));

		$values = implode("','",$data);

		$sql = "insert into ".$this->table." (".$key.") values('".$values."')";

		$this->exec($sql);

	}

	public function delete($id)
	{
		$pri_key = $this->get_pri_key();

		$sql = "delete from ".$this->table." where ".$pri_key."=".$id;

		$this->exec($sql);

	}

	public function get_pri_key()
	{
		$sql = "desc ".$this->table;

		$res = $this->query($sql);

		foreach ($res as  $v){
			if($v['Key']=='PRI'){
				return $v['Field'];
			}
		}
	}

	public function save($data,$id)
	{
		$str = '';
		foreach ($data as $k => $v) {
			$str .= $k."='".$v."',";
		}
		$str = rtrim($str,',');

		$sql = "update ".$this->table." set ".$str." where ".$this->get_pri_key()."=".$id;

		$this->exec($sql);
	}

	public function findAll($where=[])
	{
		
		if(is_array($where)){
			$str = '';
			foreach ($where as $k => $v) {
				$str .= ' '.$k."='".$v."' and";
			}
			$str = rtrim($str,'and');

			$sql = "select * from ".$this->table. " where".$str;

		}else if($where){
			$sql = "select * from ".$this->table.' limit '.$where;
		}else{
			$sql = "select * from ".$this->table;
		}

		// var_dump($sql);
		
		return $this->query($sql);
	}

	public function find($data)
	{
		if(is_int($data)){
			$sql = "select * from ".$this->table ." where ".$this->get_pri_key()."=".$data." limit 1";
		}else{
			$sql = "select * from ".$this->table ." limit 1";
		}
		return current($this->query($sql));
	}

	public function query($sql)
	{
		$res = $this->db->query($sql);

		if($res==false){
			var_dump($this->db->errorInfo());
		}else{
			return $res->fetchAll(PDO::FETCH_ASSOC);
		}
	}

	public function exec($sql)
	{
		$res = $this->db->exec($sql);

		if($res==false){
			var_dump($this->db->errorInfo());
		}else{
			return true;
		}
	}
}